package com.kingsalert.kingsalert.analytics.data_sdk.task;

import android.content.Context;
import android.text.TextUtils;

import com.kingsalert.kingsalert.analytics.data_sdk.beans.ASRequestPms;
import com.kingsalert.kingsalert.analytics.data_sdk.http.ASReqstManger;
import com.kingsalert.kingsalert.analytics.data_sdk.logger.ASLger;
import com.kingsalert.kingsalert.analytics.data_sdk.services.ASBtryIfo;
import com.kingsalert.kingsalert.config.CountryConfig;
import com.kingsalert.kingsalert.config.Paths;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

public class ASDevcBtyTsk implements Supplier<String> {

    private final static String TAG = "ASDeviceBatteryTask";

    private final String mTaskId;
    private final Context mContext;

    public ASDevcBtyTsk(Context context, String taskId) {
        this.mContext = context;
        this.mTaskId = taskId;
    }

    @Override
    public String get() {
        // 日志标记
        ASLger.d(TAG, TAG + " 执行中...");

        // 过滤条件
        if (TextUtils.isEmpty(Paths.PATH_BATTERY)) {
            return mTaskId + "";
        }

        // 创建任务
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        CountDownLatch latch = new CountDownLatch(1);
        AsyncBtyTsk asyncTask = new AsyncBtyTsk(mContext, latch, mTaskId);
        executorService.submit(asyncTask);

        // 等待任务完成
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return mTaskId + "";
    }

    static class AsyncBtyTsk implements Runnable {
        private final CountDownLatch latch;
        private final Context mContext;
        private final String mTaskId;

        AsyncBtyTsk(Context context, CountDownLatch latch, String taskId) {
            this.mContext = context;
            this.latch = latch;
            this.mTaskId = taskId;
        }

        @Override
        public void run() {
            ASBtryIfo batteryInfo = new ASBtryIfo();
            batteryInfo.getBatteryInfo(mContext, batteryInfoBean -> {
                ASRequestPms netParams = new ASRequestPms();
                netParams.setDBG(batteryInfoBean);
//                String result = new Gson().toJson(netParams).trim();
                String result = netParams.toEncryptParams(Paths.PATH_BATTERY);

                CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                    String url = CountryConfig.getInstance().getCommonPath();
                    new ASReqstManger.Builder().setReqId(this.mTaskId).setUrl(url).setBody(result).build().doPostRqst();

                    return mTaskId + "";
                });

                future.thenRun(latch::countDown);
            });

        }
    }
}
